Java for Beginners: by Knowledge flow by flow Knowledge
Control Statements
There three types of statements in java.
Selection statements
Iteration statements
Jump statements
Selection statements
It is to manage the flow of programs that is to be executed based on the dynamic conditions which can be only realized during the run time.
It provides flexibility.
If statement- It provides different paths for execution of program.
Syntax
If (condition provided) statement a;
Else
Statement b;
This means if the condition is true, then statement a is executed but if false then statement b is executed.
For example
int a, b;
If (x < y) a=0;
Else
b=0;
Now there is one type of procedure using if statement i.e. nested if statement and it is very common method in programming world.
For example
If (a == 10) {
If (b < 15) i = j;
If (c > 50) p = q;
Else
i = p;
}
Else
i = q;
Now, the second if statement in the parenthesis is associated with else. Another type of procedure is of using if statement is the if-else-if ladder statement.
For example
If (condition)
Statement;
Else if (condition)
Statement;
Else if (condition)
Statement;
.
.
.
.
.
Else
Statement;
Switch statements
It is a multi branched statement.
Syntax
Switch (expression)
{
Case value 1:
Statement
Break;
Case value 2:
Statement
Break;
.
.
.
Case vale n:
Statement
Break;
Default:
Statement;
}
The functioning of the switch statement is compares the given value with all the cases and when the match found the program sequence is executed.
For example
Class sampswitch {
Public static void main (string args [])
{
Switch (i)
{
Case0:
System.out.println (“i is zero.”);
Break;
Case1:
System.out.println(“i is one.”)
Break;
Default:
System.out.println (“i is greater than 4.”)
}
Output
i is zero.
i is one.
i is greater than 4.
i is greater than 4.
Example of nested switch loop program
Switch (countfigures)
{
Case 1:
Switch (targetvalue)
{//nested switch//
Case 0:
System.out.println (“target is zero”;
Break;
Case 1:
System.out.println (“target is one”;
Break;
}
Break;
Case 2: //...
Important features of switch statement are.
Switch statement can only check for equality unlike if.
There cannot be two cases constant in the same switch with identical values.
It is more effective than using the set of nested if statement.